package com.tencent.sr.iris.activity.common.util;

import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Map;

/**
 * 描述用途
 *
 * @author wruiiwang
 * @date 2023/2/14
 */
@Slf4j
public class SpelUtil {

    // SpelExpressionParser——SpEL parser. Instances are reusable and thread-safe.
    public static final ExpressionParser parser = new SpelExpressionParser();

    public static Boolean spelJudge(String spel, Map<String, Object> map) {
        log.info("spel:{},variables:{}", spel, map);
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariables(map);
        Boolean value = parser.parseExpression(spel).getValue(context, Boolean.class);
        return value;
    }

    public static void main(String[] args) {
        String spel = "#commission > #targetCommission && #share > #targetShare";
        System.out.println(spelJudge(spel, ImmutableMap.of()));
        System.out.println(spelJudge(spel, ImmutableMap.of("commission", 10)));
        System.out.println(spelJudge(spel, ImmutableMap.of("commission", 10, "targetCommission", 8)));
        System.out.println(spelJudge(spel, ImmutableMap.of("commission", 10, "targetCommission", 8,
                "targetShare", 18)));
        System.out.println(spelJudge(spel, ImmutableMap.of("commission", 10, "targetCommission", 8,
                "share", 20, "targetShare", 18)));
    }
}
